package com.ruoyi.mobile.controller;


import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.css.mobile.system.dto.RegisterDTO;
import org.css.mobile.system.service.MobileLoginService;
import org.css.mobile.system.dto.SignUpDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/mobile")
@Api(tags = "手机端通用接口")
public class MobileSignUpController extends BaseController {

    @Autowired
    private MobileLoginService mobileLoginService;

    /**
     * 登录方法
     *
     * @param signUpVO 登录信息
     * @return 结果
     */
    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody SignUpDTO signUpVO)
    {
        AjaxResult ajax = success();
        // 生成令牌
        String token = mobileLoginService.login(signUpVO.getUsername(), signUpVO.getPassword());
        ajax.put(Constants.TOKEN, token);
        ajax.put("user", getLoginUser());
        return ajax;
    }

    @ApiOperation(value = "注册")
    @PostMapping("/register")
    public AjaxResult register(@RequestBody @Valid RegisterDTO registerDTO)
    {
        // 校验参数
        if (!registerDTO.getPassword().equals(registerDTO.getRePassword())) {
            return error("两次密码不一致");
        }

        // 封装系统对象
        SysUser sysUser = new SysUser();
        sysUser.setUserName(registerDTO.getUsername());
        sysUser.setPassword(registerDTO.getPassword());

        // 注册用户
        String msg = mobileLoginService.register(sysUser);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }


}
